<template>
  <div>
    <h1>评价页面</h1>
    <el-button type="primary" @click="openCreateReview">新建评价</el-button>
    <el-table :data="reviews" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="reviewId" label="评价ID"></el-table-column>
      <el-table-column prop="patientId" label="病人ID"></el-table-column>
      <el-table-column prop="doctorName" label="医生姓名"></el-table-column>
      <el-table-column prop="rating" label="评分"></el-table-column>
      <el-table-column prop="content" label="评价"></el-table-column>
      <el-table-column prop="reviewTime" label="评价时间"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope" style="width: 100%;">
          <el-button type="primary" @click="openEditReview(scope.row)">修改评价</el-button>
          <el-button type="danger" @click="deleteReview(scope.row.reviewId)">删除评价</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="新建评价" v-model="showCreateReviewDialog" width="500">
      <el-form>
        <el-form-item label="科室" :label-width="formLabelWidth">
          <el-select v-model="newComment.departmentId" placeholder="请选择科室" @change="fetchDoctors">
            <el-option v-for="department in departments" :key="department.id" :label="department.name" :value="department.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="医生" :label-width="formLabelWidth">
          <el-select v-model="newComment.doctorId" placeholder="请选择医生" @change="handleDoctorChange">
            <el-option v-for="doctor in doctors" :key="doctor.userId" :label="doctor.name" :value="doctor.userId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="评分">
          <el-rate v-model="newComment.rating" :max="5"></el-rate>
        </el-form-item>
        <el-form-item label="评价">
          <el-input type="textarea" v-model="newComment.content" placeholder="请填写评价"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitReview">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改评价对话框 -->
    <el-dialog title="修改评价" v-model="showEditReviewDialog" width="500">
      <el-form>
        <el-form-item label="医生" :label-width="formLabelWidth">
          <el-input v-model="editComment.doctorName" disabled></el-input>
        </el-form-item>

        <el-form-item label="评分">
          <el-rate v-model="editComment.rating" :max="5"></el-rate>
        </el-form-item>
        <el-form-item label="评价">
          <el-input type="textarea" v-model="editComment.content" placeholder="请填写评价"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditReview">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElButton, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElSelect, ElOption, ElRate, ElInput } from 'element-plus';

export default {
  name: 'CommentPage',
  components: {
    ElButton,
    ElTable,
    ElTableColumn,
    ElDialog,
    ElForm,
    ElFormItem,
    ElSelect,
    ElOption,
    ElRate,
    ElInput,
  },
  data() {
    return {
      reviews: [],
      showCreateReviewDialog: false,
      showEditReviewDialog: false,
      newComment: {
        departmentId: null,
        doctorId: null,
        doctorName: '',
        rating: null,
        content: ''
      },
      editComment: {
        reviewId: null,
        doctorId: null,
        doctorName: '',
        rating: null,
        content: ''
      },
      departments: [
        { id: 1, name: '内科' },
        { id: 2, name: '外科' },
        { id: 3, name: '儿科' },
        { id: 4, name: '妇产科' },
        { id: 5, name: '眼科' },
        { id: 6, name: '耳鼻喉科' },
        { id: 7, name: '皮肤科' },
        { id: 8, name: '精神科' },
        { id: 9, name: '骨科' },
        { id: 10, name: '急诊科' }
      ],
      doctors: [],
      rating: 0,
      comment: '',
    };
  },
  created() {
    this.fetchReviews();
  },
  methods: {
    openEditReview(review) {
      this.editComment = { ...review };
      const doctor = this.doctors.find(doc => doc.userId === review.doctorId);
      if (doctor) {
        this.editComment.doctorName = doctor.name;
      }
      this.showEditReviewDialog = true;
    },
    async submitEditReview() {
      if (!this.editComment.doctorId || !this.editComment.rating || this.editComment.content.trim() === '') {
        ElMessage.error('请填写完整信息');
        return;
      }

      const updatedReview = {
        patientId: this.editComment.patientId,
        doctorId: this.editComment.doctorId,
        rating: this.editComment.rating,
        content: this.editComment.content,
      };

      try {
        await axios.put(`http://localhost:8085/api/review/update?id=${this.editComment.reviewId}`, updatedReview);
        ElMessage.success('评价修改成功');
        this.showEditReviewDialog = false;
        this.fetchReviews();
      } catch (error) {
        ElMessage.error('评价修改失败');
      }
    },
    async fetchReviews() {
      const response = await axios.get('http://localhost:8085/api/review/getByPatientId', {
        params: {
          id: this.$store.state.id
        }
      });
      this.reviews = response.data;

      // 获取医生列表，确保医生信息在修改评价时可用
      const departmentIds = [...new Set(this.reviews.map(review => review.departmentId))];
      for (const departmentId of departmentIds) {
        await this.fetchDoctors(departmentId);
      }

      // 设置每条评价的医生名称
      this.reviews.forEach(review => {
        const doctor = this.doctors.find(doc => doc.userId === review.doctorId);
        if (doctor) {
          review.doctorName = doctor.name;
        }
      });
    },
    async fetchDoctors(departmentId) {
      try {
        const response = await axios.get(`http://localhost:8085/api/doctor/specialty/${departmentId}`);
        this.doctors = [...this.doctors, ...response.data.data];
      } catch (error) {

      }
    },
    openCreateReview() {
      this.showCreateReviewDialog = true;
    },
    handleDoctorChange(doctorId) {
      const selectedDoctor = this.doctors.find(doctor => doctor.userId === doctorId);
      if (selectedDoctor) {
        this.newComment.doctorId = selectedDoctor.userId;
        this.newComment.doctorName = selectedDoctor.name;
      }
    },
    async submitReview() {
      if (!this.newComment.doctorId || !this.newComment.rating || this.newComment.content.trim() === '') {
        ElMessage.error('请填写完整信息');
        return;
      }

      const newReview = {
        patientId: this.$store.state.id,
        doctorId: this.newComment.doctorId,
        doctorName: this.newComment.doctorName,
        rating: this.newComment.rating,
        content: this.newComment.content,
      };

      try {
        await axios.post('http://localhost:8085/api/review/create', newReview);
        ElMessage.success('评价提交成功');
        this.showCreateReviewDialog = false;
        this.fetchReviews();
      } catch (error) {
        ElMessage.error('评价提交失败');
      }
    },
    async deleteReview(id) {
      try {
        const response = await axios.delete(`http://localhost:8085/api/review/delete` + {
          params: { id }
        });
        if (response.data.code === 1) {
          ElMessage.success('评价删除成功');
          this.fetchReviews();
        } else {
          ElMessage.error('评价删除失败');
        }
      } catch (error) {
        if (error.response) {
          // 服务器响应了一个状态码，但状态码表示一个错误
          ElMessage.error(`删除失败: ${error.response.data.message}`);
        } else if (error.request) {
          // 请求已经发出，但没有收到响应
          ElMessage.error('网络错误，请检查您的网络连接');
        } else {
          // 其他错误
          ElMessage.error(`删除失败: ${error.message}`);
        }
      }
    },
  },
};
</script>

<style scoped>
</style>